<template>
  <div>
    <el-upload
      action=""
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="handlePreview"
      :on-remove="handelRemove"
      :on-change="handelChange"
      :before-upload="beforeUpload"
      :http-request="handelRequest"
      :limit="limit"
      :class="{disabled:abc}"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="showDialog" title="图片预览">
      <img :src="url" alt="" style="width:100%">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)
const cos = new COS({
  SecretId: 'AKIDpTu5zcy3qMbZGgrmQntjHYXFgqjKeiV1', // 身份识别ID
  SecretKey: 'HI2VhcGdjX4KJ0QZQ0JYXEfphIcgSxB8' // 身份秘钥
})
export default {
  props: {
    limit: {
      type: Number,
      default: 2
    }
  },
  data() {
    return {
      fileList: [],
      showDialog: false,
      url: ''
    }
  },
  computed: {
    abc() {
      return this.fileList.length >= this.limit
    },
    uploadAllSuccess() {
      return this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    handlePreview(file) {
      // console.log(file)
      this.showDialog = true
      this.url = file.url
    },
    handelRemove(file, fileList) {
      // this.fileList = [...fileList]
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    handelRequest(obj) {
      // console.log(obj)
      // if (obj.file) {
      // 执行上传操作
      const old = this.fileList.find(item => item.uid === obj.file.uid)
      console.log(old)
      cos.putObject({
        Bucket: 'tingzhi-1312769953', // 存储桶的名字
        Region: 'ap-nanjing', // 存储桶地域
        Key: Math.floor(Math.random() * 1000) + '-' + obj.file.name, // 上传到存储桶的文件名, 如果希望不重名, 可以对文件名进行处理
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: obj.file, // 上传的文件对象
        // 上传的进度, 上传的过程中实时触发onProgress, 可以做进度条的展示
        onProgress: progressData => {
          console.log(progressData)
          old.status = 'uploading'
          old.percentage = Math.floor(progressData.percent * 100)
          // this.percent = parseInt(progressData.percent * 100)
        }
      }, (err, data) => {
        if (err) return
        old.status = 'success'
        old.url = 'https://' + data.Location
        console.log('上传成功')
      })
      // }
    },
    handelChange(file, fileList) {
      this.fileList = [...fileList]
    },
    beforeUpload(file) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传的图片格式, 必须是jpg, gif, bmp, png的格式!')
        return false
      }
      if (file.size / 1024 / 1024 >= 5) {
        this.$message.error('上传头像过大, 超过了5M, 必须5M以内')
        return false
      }
      return true
    }
  }
}
</script>
<style lang="scss" scoped>
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none
    }
  }
}
</style>
